package com.ruoyi.project.pay.weixin;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.ruoyi.project.pay.common.util.BigDecimalUtil;
import com.ruoyi.project.pay.weixin.modal.MyConfigModal;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 张泽宇
 * 申请退款
 * @date 2020/9/29 14:59
 */
@Slf4j
public class WxRefundMoney {


    //申请退款
    /**
     * @return
     * @throws Exception
     */
    public String refund(MyConfigModal myConfigModal) throws Exception {


        Map<String, String> responseMap = new HashMap<>();
        Map<String, String> requestMap = new HashMap<>();

        WXPayConfig wxPayConfig = myConfigModal;
        WXPay wxpay = new WXPay(wxPayConfig);
        requestMap.put("out_trade_no", myConfigModal.getOrderNo());//商品订单号
        requestMap.put("out_refund_no", myConfigModal.getRefundOrderNo());//商户退单号
        String totalFee = BigDecimalUtil.mul(myConfigModal.getTotalFee(), "100", 0);
        String refundFee = BigDecimalUtil.mul(myConfigModal.getRefundFee(), "100", 0);
        requestMap.put("total_fee", totalFee);//订单金额
        requestMap.put("refund_fee", refundFee);//退款金额
        requestMap.put("refund_desc", myConfigModal.getRefundReason());//退款原因
        try {
            responseMap = wxpay.refund(requestMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String return_code = responseMap.get("return_code");   //返回状态码
        String return_msg = responseMap.get("return_msg");     //返回信息
        if ("SUCCESS".equals(return_code)) {
            String result_code = responseMap.get("result_code");       //业务结果
            String err_code_des = responseMap.get("err_code_des");     //错误代码描述
            if ("SUCCESS".equals(result_code)) {
                //表示退款申请接受成功，结果通过退款查询接口查询
                //修改用户订单状态为退款申请中或已退款。退款异步通知根据需求，可选

                // result.setResult(jsonObject);
                // return result.ok("退款申请成功");
                return "success";
            } else {
                log.error("订单号:{} 错误信息:{}" , myConfigModal.getOrderNo() , err_code_des);
                //return Result.error(err_code_des);
                return "error";
            }
        } else {
            log.info("订单号:{} 错误信息:{}" ,myConfigModal.getOrderNo(),return_msg );
            return "error";
        }
    }

}
